package com.atguigu.gmall.pay.service.impl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.atguigu.gmall.common.util.DateUtil;
import com.atguigu.gmall.feign.order.OrderFeignClient;
import com.atguigu.gmall.order.entity.OrderInfo;
import com.atguigu.gmall.pay.config.properties.AlipayProperties;
import com.atguigu.gmall.pay.service.PayService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

@Service
@Slf4j
public class PayServiceImpl implements PayService {

    @Autowired
    OrderFeignClient orderFeignClient;

    @Autowired
    AlipayClient alipayClient;

    @Autowired
    AlipayProperties alipayProperties;

    @Override
    public String generatePayPage(Long orderId, Long userId) throws AlipayApiException {
        //1.创建AliPayClient

        //2.创建支付请求
        AlipayTradePagePayRequest alipayTradePagePayRequest = new AlipayTradePagePayRequest();

        //3.设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        //3.1 //同步回调：支付成功后浏览器跳转到那个而地址
        alipayRequest.setReturnUrl(alipayProperties.getReturn_url());
        //3.2 //通知回调：支付成功后消息通知给那个地址
        alipayRequest.setNotifyUrl(alipayProperties.getNotify_url());

        //4. 准备待支付的订单数据,远程调用订单服务，
        OrderInfo orderInfo = orderFeignClient.getOrderInfoById(orderId).getData();
        //商户订单号
        String outTradeNo = orderInfo.getOutTradeNo();
        //付款金额
        BigDecimal totalAmount = orderInfo.getTotalAmount();
        //订单名称
        String orderName = "尚品汇-订单-" + outTradeNo;
        //商品描述
        String tradeBody = orderInfo.getTradeBody();
        String date = DateUtil.formatDate(orderInfo.getExpireTime(), "yyyy-MM-dd HH:mm:ss");
        // 补充了自动关单功能
        alipayRequest.setBizContent("{\"out_trade_no\":\""+ outTradeNo +"\","
                + "\"total_amount\":\""+ totalAmount +"\","
                + "\"subject\":\""+ orderName +"\","
                + "\"body\":\""+ tradeBody +"\","
                + "\"time_expire\":\""+ date +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        String page = alipayClient.pageExecute(alipayRequest).getBody();
        log.info("发送page请求：{}",page);
        return page;
    }
}
